package org.tale.mscp.sms.aliyun;


import com.google.gson.*;
import com.google.gson.annotations.Expose;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * JSON转换类
 *
 * @author WH
 */
@Component
public class GsonUtils {

    public static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    public static Gson publicGson = new Gson();

    public Gson InitGsonFliter(Class<?>... c) {
        return new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
                .addSerializationExclusionStrategy(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes f) {
                        // 这里作判断，决定要不要排除该字段,return true为排除
                        if ("key".equals(f.getName())) return true; //按字段名排除
                        Expose expose = f.getAnnotation(Expose.class);
                        if (expose != null && expose.deserialize() == false) return true; //按注解排除
                        return false;
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> clazz) {
                        // 直接排除某个类 ，return true为排除
                        for (Class<?> cs : c) {
                            if (clazz == cs) {
                                return true;
                            }
                        }
                        return false;
                    }
                })
                .create();
    }

    public static <T> List<T> fromListJson(String json, Class<T[]> type) {
        T[] list = new Gson().fromJson(json, type);
        return new ArrayList<T>(Arrays.asList(list));
        //List<T> list=gson.fromJson(json, new TypeToken<List<T>>(){}.getType());
        //return list;
    }

    public static Map<String, Object> fromMapJson(String json) {
        return gson.fromJson(json, new TypeToken<Map<String, Object>>() {
        }.getType());
    }

    public static <T> T fromJson(String json, Class<T> type) {
        return publicGson.fromJson(json, type);
    }

    public static <T> T fromJson(JsonElement jsonElement, Class<T> type) {
        return publicGson.fromJson(jsonElement, type);
    }

    public static String toJson(Object src) {
        return publicGson.toJson(src);
    }
}
